/*
 * Copyright (c) 2018-2999 湖南洛云网络科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.platform.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.model.NotifyTemplate;
import com.yami.shop.common.annotation.SysLog;

import javax.validation.Valid;

import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.service.NotifyTemplateService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import lombok.AllArgsConstructor;

import java.util.*;


/**
 *
 *
 * @author lhd
 * @date 2020-07-01 16:13:08
 */
@RestController
@AllArgsConstructor
@RequestMapping("/platform/notifyTemplate")
public class NotifyTemplateController {

    private final NotifyTemplateService notifyTemplateService;

    /**
     * 分页查询
     * @param page 分页对象
     * @return 分页数据
     */
    @GetMapping("/page" )
    public ResponseEntity<IPage<NotifyTemplate>> getNotifyTemplatePage(PageParam<NotifyTemplate> page, NotifyTemplate notifyTemplate) {

        IPage<NotifyTemplate> templatePage = notifyTemplateService.page(page, new LambdaQueryWrapper<NotifyTemplate>()
                .eq(Objects.nonNull(notifyTemplate.getSendType()),NotifyTemplate::getSendType,notifyTemplate.getSendType())
                .ne(NotifyTemplate::getSendType, SendType.CUSTOMIZE.getValue())
                .orderByDesc(NotifyTemplate::getStatus).orderByDesc(NotifyTemplate::getCreateTime));
        if(CollectionUtils.isEmpty(templatePage.getRecords())){
            return ResponseEntity.ok().build();
        }
        for (NotifyTemplate  template: templatePage.getRecords()) {
            List<Integer> templateList = getTemplateList(template.getTemplateTypes());
            for (Integer type : templateList) {
                template.setSms(type == 1 ? true:template.getSms());
                template.setSub(type == 2 ? true:template.getSub());
                template.setApp(type == 3 ? true:template.getApp());
            }
            template.setTemplateTypeList(templateList);
        }
        return ResponseEntity.ok(templatePage);
    }

    private List<Integer> getTemplateList(String templateTypes) {
        String[] templateTypeList = templateTypes.split(StrUtil.COMMA);
        List<String> asList = Arrays.asList(templateTypeList);
        List<Integer> templates = new ArrayList<>();
        for (String templateStr : asList) {
            templates.add(Integer.valueOf(templateStr));
        }
        return templates;
    }


    /**
     * 通过id查询
     * @param templateId id
     * @return 单个数据
     */
    @GetMapping("/info/{templateId}" )
    public ResponseEntity<NotifyTemplate> getById(@PathVariable("templateId") Long templateId) {
        NotifyTemplate template = notifyTemplateService.getById(templateId);
        template.setTemplateTypeList(getTemplateList(template.getTemplateTypes()));
        return ResponseEntity.ok(template);
    }

    /**
     * 新增
     * @param notifyTemplate
     * @return 是否新增成功
     */
    @SysLog("新增" )
    @PostMapping
    @PreAuthorize("@pms.hasPermission('platform:notifyTemplate:save')" )
    public ResponseEntity<Boolean> save(@RequestBody @Valid NotifyTemplate notifyTemplate) {
        notifyTemplate.setCreateTime(new Date());
        notifyTemplate.setStatus(1);
        if(CollectionUtils.isEmpty(notifyTemplate.getTemplateTypeList())){
            // 请至少选择一种通知方式
            throw new YamiShopBindException("yami.select.notify.check");
        }
        List<NotifyTemplate> notifyTemplates = notifyTemplateService.list(new LambdaQueryWrapper<NotifyTemplate>().eq(NotifyTemplate::getSendType, notifyTemplate.getSendType()));
        if(CollectionUtils.isNotEmpty(notifyTemplates)){
            // 已经存在当前消息类型的短信，请去进行修改操作
            throw new YamiShopBindException("yami.select.notify.type.check");
        }
        SendType sendType = SendType.instance(notifyTemplate.getSendType());
        if(Objects.nonNull(sendType)) {
            notifyTemplate.setMsgType(sendType.getType());
        }
        notifyTemplate.setTemplateTypes(arrayChangeList(notifyTemplate.getTemplateTypeList()));
        return ResponseEntity.ok(notifyTemplateService.save(notifyTemplate));
    }

    /**
     * 修改
     * @return 是否修改成功
     */
    @SysLog("修改" )
    @PutMapping
    @PreAuthorize("@pms.hasPermission('platform:notifyTemplate:update')" )
    public ResponseEntity<Boolean> updateById(@RequestBody @Valid NotifyTemplate notifyTemplate) {
        if(CollectionUtils.isEmpty(notifyTemplate.getTemplateTypeList())){
            // 请至少选择一种通知方式
            throw new YamiShopBindException("yami.select.notify.check");
        }
        List<NotifyTemplate> notifyTemplates = notifyTemplateService.list(new LambdaQueryWrapper<NotifyTemplate>()
                .eq(NotifyTemplate::getSendType, notifyTemplate.getSendType()).ne(NotifyTemplate::getTemplateId,notifyTemplate.getTemplateId()));
        if(CollectionUtils.isNotEmpty(notifyTemplates)){
            // 已经存在当前消息类型的短信，请去进行修改操作
            throw new YamiShopBindException("yami.select.notify.type.check");
        }
        notifyTemplate.setTemplateTypes(arrayChangeList( notifyTemplate.getTemplateTypeList()));
        SendType sendType = SendType.instance(notifyTemplate.getSendType());
        if(Objects.nonNull(sendType)) {
            notifyTemplate.setMsgType(sendType.getType());
        }
        return ResponseEntity.ok(notifyTemplateService.updateById(notifyTemplate));
    }

    private String arrayChangeList(List<Integer> templateTypeList) {
        StringBuilder templateTypes = new StringBuilder();
        for (Integer templateType : templateTypeList) {
            templateTypes.append(templateType);
            templateTypes.append(StrUtil.COMMA);
        }
        templateTypes.deleteCharAt(templateTypes.length() - 1);
        return templateTypes.toString();
    }

    /**
     * 通过id状态变更
     * @param templateId id
     * @return 是否修改成功
     */
    @SysLog("状态变更" )
    @DeleteMapping("/{templateId}" )
    @PreAuthorize("@pms.hasPermission('platform:notifyTemplate:updateSts')" )
    public ResponseEntity<Boolean> removeById(@PathVariable Long templateId) {
        NotifyTemplate template = notifyTemplateService.getById(templateId);
        template.setStatus(template.getStatus() == 1? 0:1);
        return ResponseEntity.ok(notifyTemplateService.updateById(template));
    }

}
